using System;
using System.Collections.Generic;
using System.IO;

namespace SolarWinds.Logging
{
    public sealed class LogManager
    {
        #region Singleton Design Pattern

        static readonly LogManager mInstance = new LogManager();

        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static LogManager()
        {
        }

        LogManager()
        {
            // create the global log
            CreateLog("Global");
        }

        ~LogManager()
        {
            mLogs.Clear();
        }

        public static LogManager Instance
        {
            get { return mInstance; }
        }

        #endregion

        private readonly Dictionary<string, Log> mLogs = new Dictionary<string,Log>();

        public void CreateLog(String logName)
        {
            if (!mLogs.ContainsKey(logName))
            {
                mLogs.Add(logName, new Log(logName));
            }
            else
            {
                Log("A log with name " + logName + " is already open. Can't open twice.");
            }
        }

        public void Log(String msg)
        {
            Log(msg, "Global");
        }

        public void Log(String msg, String logName)
        {
            if (mLogs.ContainsKey(logName) && 
                mLogs[logName] != null)
            {
                mLogs[logName].WriteLine(msg);
            }
            else
            {
                Log("No log with name " + logName + " exists -> logging to Global log.");
                Log(msg);
            }
        }

        public void RemoveLog(String logName)
        {
            mLogs.Remove(logName);
        }

        public void ClearAllLogs()
        {
            mLogs.Clear();
        }

        public StreamWriter GetStreamWriter()
        {
            return GetStreamWriter("Global");
        }

        public StreamWriter GetStreamWriter(String logName)
        {
            if (mLogs.ContainsKey(logName) &&
                mLogs[logName] != null)
            {
                return mLogs[logName].StreamWriter;
            }

            return null;
        }
    }
}